package com.tarena.lbs.business.dao.repository.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tarena.lbs.business.dao.mapper.StoreMapper;
import com.tarena.lbs.business.dao.repository.StoreRepository;
import com.tarena.lbs.business.pojo.po.StorePO;
import com.tarena.lbs.business.pojo.query.StoreQuery;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

@Slf4j
@Repository
public class StoreRepositoryImpl implements StoreRepository {
    @Autowired
    private StoreMapper storeMapper;

    @Override
    public void save(StorePO po) {
        storeMapper.insert(po);
    }

    @Override
    public PageInfo<StorePO> pagesList(StoreQuery query) {
        log.info("查询店铺列表数据层,入参:{}",query);
        QueryWrapper<StorePO> queryWrapper = assembleStoreQuery(query);
        //PageHelper.startPage 之间不能有代码
        PageHelper.startPage(query.getPageNo(), query.getPageSize());
        List<StorePO> pos = storeMapper.selectList(queryWrapper);
        //selectList 数据库操作 之间不能有代码
        return new PageInfo<>(pos);
    }

    @Override
    public StorePO getDetail(Integer id) {
        return  storeMapper.selectById(id);
    }

    @Override
    public int delete(Integer id) {

        return storeMapper.delete(id);
    }

    @Override
    public int updateStatus(Integer id) {
        return storeMapper.updateStatus(id);
    }

    private QueryWrapper<StorePO> assembleStoreQuery(StoreQuery query) {
        QueryWrapper<StorePO> queryWrapper = new QueryWrapper<>();
        //1.business_id 商家id 条件查询 非空 where business_id = #{businessId}
        if (query.getBusinessId() != null){
            queryWrapper.eq("business_id",query.getBusinessId());
        }
        //2.store_name 店铺名称 模糊查询 非空 where store_name like '%${storeName}%'
        if (query.getStoreName() != null){
            queryWrapper.like("store_name",query.getStoreName());
        }
        //3.store_head_phone 负责人电话 模糊查询 非空 where store_head_phone like '%${storeHeadPhone}%'
        if (query.getStoreHeadPhone() != null){
            queryWrapper.like("store_head_phone",query.getStoreHeadPhone());
        }
        //4.create_time 入驻时间 条件查询 非空 where create_time between #{startingTime} and #{endTime}
        if (query.getStartingTime() != null && query.getEndTime() != null){
            queryWrapper.between("create_time",query.getStartingTime(),query.getEndTime());
        }
        //5.store_status 店铺状态 0:启用 -1:禁用
        if (query.getStoreStatus() != null){
            queryWrapper.eq("store_status",query.getStoreStatus());
        }
        return queryWrapper;
    }
}
